package net.gdface.service.search;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import net.gdface.service.client.FetchImage;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SearchImgImpl360So extends SearchImgImpl {
	private static final Logger logger = LoggerFactory.getLogger(SearchImgImpl360So.class);
	private static final List<NameValuePair> constantsParameters=constantsParameters();
	private static final URI SE_IMAGE_PAGE;
	private static final URI SE_IMAGE_URI_FOR_JSON;
	private static final int PAGE_SIZE = 80;
	static {
		try {
			SE_IMAGE_PAGE = new URIBuilder("http://image.haosou.com/i").setParameter("src", "srp").build();
			SE_IMAGE_URI_FOR_JSON =	new URIBuilder("http://image.haosou.com/j")
				.setParameters(constantsParameters)
				.build();
		} catch (URISyntaxException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public SearchImgImpl360So(String keyword, SearchSimilarImg simProcessor, FetchImage saveProcessor) {
		super(keyword, simProcessor, saveProcessor);
	}
	
	@Override
	protected URI createHTMLUri() {
		try {
			return new URIBuilder(SE_IMAGE_PAGE).setParameter("q", keyword).build();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}
	
	@Override
	protected URI nextPage(URI lastPage, int startIndex) {
		try {
			URI target = (null==lastPage)?	new URIBuilder(SE_IMAGE_URI_FOR_JSON).setParameter("q", keyword).build():lastPage;
			return new URIBuilder(target).setParameter("sn", Integer.toString(startIndex)).build();
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}
	@Override
	protected String getArrayKey() {
		return "list";
	}

	@Override
	protected String getResNumKey() {
		return "total";
	}
	
	private static List<NameValuePair> constantsParameters() {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("src", "srp"));
		nvps.add(new BasicNameValuePair("zoom", "0"));
		nvps.add(new BasicNameValuePair("pn", Integer.toString(PAGE_SIZE)));
		return nvps;
	}

	@Override
	protected boolean isLast() {
		try {
			return ((this.totalImage>0&&this.startIndex>=this.totalImage)||(null!=jsonResp&&jsonResp.getBoolean("end")));
			//return null!=jsonResp&&jsonResp.getBoolean("end");
		} catch (JSONException e) {
			logger.error(String.format("CAN'T GET 'end' flag from JSON %s", e.toString()));
			throw new RuntimeException(e);
		}

	}

	@Override
	protected int getPageSize() {
		return PAGE_SIZE;
	}

	@Override
	protected boolean isValidResp() {
		return true;
	}


}
